<?php
/**
 * 分组
 * @author Administrator
 *
 */

class RoleController extends AdminBaseController {
	
	public function index(){
		$this->setTitle('分组列表', 'Role list');
	
		$grid   = new PubGrid();
		$filter = new PubFilter();
	
		$identityList = RoleaService::identityList();
        $identityList = array(''=>'所有') + $identityList;
        $filter->addFilter('RoleName', 'input', PubFunc::t('分组名：'), array('placeholder' => PubFunc::t(''), 'style' => 'width: 180px;'));
        $filter->addFilter('identity', 'select', '分组身份：', array('value' => '', 'options' => array('' => '所有') + $identityList));
		$params = $filter->get();
		 
		$page = $this->R('page', '1');
		$m = $this->R('m');
		$params['m'] = $m;
		$header = RoleaService::indexHeader();
		if(PubFunc::isAjax()){
			$result = RoleaService::indexData($params);
			$this->out = array(
					'count'     => $result['count'],
					'data'      => $result['data'],
					'result'    => true
			);
			$this->outType = 'json';
		}else{
			$order  = 'AddTime';
			$url = PubFunc::ajaxUrl("?r=role/index", $params);
			$grid->addGrid($header, $url, array(
					'name'=>'数据',
					'order'=>array($order, 'desc'),
					'type'=>'role/index',
					'length'=>50,
					'page'=>$page
			));
	
			$this->out['filter'] = $filter->show();
			$this->out['grid'] = $grid->show();
	
		}
	}
	


    /**
     * 新增用户
     */
    public function add() {
        $form = new PubForm();

        $identityList = RoleaService::identityList();
        $viewAllChannelList = RoleaService::viewAllChannelList();
        
        $user = AccAuth::me();
        $user_role_obj = new ModUserRoleMap();
        $role_obj = new ModRole();
        $user_role_list = $user_role_obj->findByAttributes(array('UserID'=>$user['UserID']));
        $role_id = $user_role_list->RoleID;
        $role_obj_list = $role_obj->findByAttributes(array('RoleID'=>$role_id));
        $identity = $role_obj_list->identity;  //用户所属角色的分组身份

        if($identity != 2 && $user['UserID'] != 1){ //用户所属角色的分组身份是2（统梦）才能在分配角色的时候使用这个2（统梦），分组身份是2的用户具备一些特殊权限
        	unset($identityList[2]);
        }
        
        $form->addItem('t1', 'title', PubFunc::t('基础信息'))
            ->addItem('RoleName', 'input', PubFunc::t('分组名'))
            ->addItem('RoleTag', 'input', PubFunc::t('运维标志'))
            ->addItem('identity', 'select', PubFunc::t('分组身份'), array('options' => $identityList, 'value' => 1))
            ->addItem('ViewAllChannel', 'select', PubFunc::t('查看全渠道'), array('options' => $viewAllChannelList, 'value' => 1))
            ->addItem('Remark', 'textarea', PubFunc::t('备注'))
            ->addOperation('提交', 'input', 'submit', 'btn btn-primary','sub')
            ->addOperation('返回', 'a', PubFunc::buildUrl("/auth/?r=role/index"), 'btn btn-default')
            //->setAction('/auth/?r=role/doAdd')
            ->setAction(PubFunc::buildBackUrl("/auth/?r=role/doAdd"))
            ->setName('role');

        $this->out['form'] = $form->show();

        $this->setTitle('新增分组', 'Add Role');
    }
    
   

    /**
     * 执行新增用户
     */
    public function doAdd(){
    	$role = $this->R('role');
    	$count = RoleaService::repeat(0, 'RoleName', $role['RoleName']);
    	if($count > 0){
    		$this->showMessage('分组名称已经存在');
    	}else{    		
    		$result = RoleaService::add($role);
    		if($result !== false){
    			$this->showMessage('新增成功', PubFunc::buildBackUrl("/auth/?r=role/index"));
    			//$this->redirect('/auth/?r=role/index');
    		}else{
    			$this->showMessage('添加失败');
    		}
    	}
        
    }

    /**
     * 修改用户
     */
    public function edit(){
        $form = new PubForm();

        $id = $this->R('id');
        $role = RoleaService::getById($id);
        $page = $this->R('page');
        
        $identityList = RoleaService::identityList();
        $viewAllChannelList = RoleaService::viewAllChannelList();
        
        $user = AccAuth::me();
        $user_role_obj = new ModUserRoleMap();
        $role_obj = new ModRole();
        $user_role_list = $user_role_obj->findByAttributes(array('UserID'=>$user['UserID']));
        $role_id = $user_role_list->RoleID;
        $role_obj_list = $role_obj->findByAttributes(array('RoleID'=>$role_id));
        $identity = $role_obj_list->identity;  //用户所属角色的分组身份 
        if($identity != 2 && $user['UserID'] != 1){ //用户所属角色的分组身份是2（统梦）才能在分配角色的时候使用这个2（统梦），分组身份是2的用户具备一些特殊权限
        	unset($identityList[2]);
        }

        if(!empty($role)){
        	
            $form->addItem('t1', 'title', PubFunc::t('基础信息'))
                ->addItem('RoleName', 'input', PubFunc::t('分组名'), array('value' => $role['RoleName'])) 
                ->addItem('RoleTag', 'input', PubFunc::t('运维标志'), array('value' => $role['RoleTag']))
                ->addItem('identity', 'select', PubFunc::t('分组身份'), array('options' => $identityList, 'value' => $role['identity']))
                ->addItem('ViewAllChannel', 'select', PubFunc::t('查看全渠道'), array('options' => $viewAllChannelList, 'value' => $role['ViewAllChannel']))
                ->addItem('Remark', 'textarea', PubFunc::t('备注'), array('value' => $role['Remark']))
                ->addValue('role[id]', $id)
                ->addOperation('提交', 'input', 'submit', 'btn btn-primary','sub')
                ->addOperation('返回', 'a', PubFunc::buildBackUrl("/auth/?r=role/index"), 'btn btn-default')
                ->setAction(PubFunc::buildBackUrl("/auth/?r=role/doEdit"))
                //->addOperation('返回', 'a', '/auth/?r=role/index&page='.$page, 'btn btn-default')
                //->setAction('/auth/?r=role/doEdit')
                ->setName('role');

            $this->out['form'] = $form->show();

            $this->setTitle('编辑分组', 'Edit User');
            
            $this->out['page'] = $page;
        }else{
            $this->showMessage('找不到分组');
        }
    }

    /**
     * 执行修改操作
     */
    public function doEdit(){
        $role = $this->R('role');
        
        $count = RoleaService::repeat($role['id'], 'RoleName', $role['RoleName']);
        if($count > 0){
        	$this->showMessage('分组名称已经存在');
        }else{
        	$result = RoleaService::edit($role);
        	$page = $this->R('page');
        	if($result !== false){
        		$this->showMessage('修改成功', PubFunc::buildBackUrl("/auth/?r=role/index"));
        	}else{
        		$this->showMessage('修改失败');
        	}
        }

    }

    public function delete(){
        $id = $this->R('id');
        
        //先查询是否有用户使用该分组，使用了则不能进行删除
        $modUserRoleMap = new ModUserRoleMap();
        $result = $modUserRoleMap->getRoleUserList($id);
        $page = $this->R('page');
        if($this->isAuth !=1){
        	if(count($result) > 0){
        		$this->showMessage('该分组下存在用户，不能进行删除',PubFunc::buildBackUrl("/auth/?r=role/index"));
        	}else{
        		if(RoleaService::delete($id)){
        			$this->showMessage('删除成功', PubFunc::buildBackUrl("/auth/?r=role/index"));
        		}else{
        			$this->showMessage('删除失败', PubFunc::buildBackUrl("/auth/?r=role/index"));
        		}
        	}
        }
        
    }
    
    public function grant(){
    	$id = $this->R('id');
    	$role = RoleaService::getById($id);
        $game = PubRequest::R('g');
        $m = PubRequest::R('m');
    	if(empty($role)){
    		$this->showMessage('分组不存在');
    	}else{
    		$this->out['role'] = $role;
    		$this->setTitle('分组菜单编辑', 'Edit Role Menu');
    		$this->out['game'] = $game;
    		$this->out['m'] = $m;
    	}
    }
    
    // 获得分组的菜单列表
    public function getGrantMenu(){
    	$roleId = $this->R('role');
    
    	$modMenu = new ModMenu();
    	
    	$user = AccAuth::me();
    	if(!AccAuth::isAdmin()){  //非超级管理员只显示他本身有的功能
    		$modRole = new ModUserRoleMap();
    		$role_obj = $modRole->findAllByAttributes(array('UserID'=>$user['UserID']));
    		$role_id = $role_obj[0]->RoleID;
    	
    		$menu = new ModRoleMenuMap();
    		$menu_obj = $menu->findAllByAttributes(array('RoleID'=>$role_id));
    		$role_menu_array = array();
    		foreach ($menu_obj as $key=>$val){
    			$role_menu_array[] = $val['MenuID'];
    		}
    	}
    	
    	$menuList = array();
    	if(!AccAuth::isAdmin()){
    		foreach($modMenu->select() as $v){
    			if($v['Visible'] == 1 && in_array($v['MenuID'], $role_menu_array)){
    				$menuList[$v['MenuID']] = $v;
    			}
    		}
    	}else{
    		foreach($modMenu->select() as $v){
    			if($v['Visible'] == 1){
    				$menuList[$v['MenuID']] = $v;
    			}
    		}
    	}
    	

    	$result  = array();
    	foreach($menuList as $v){
    		$result[$v['ParentID']][$v['MenuID']] = $v;
    	}
    
    	$checked = MenuService::getRoleMenu($roleId);
    
    	echo $this->echoTree($result, '0', 'MenuID', 'MenuName', $checked, true);
    	$this->outType = 'ajax';
    }
    
    /**
     * 打印树级结构
     * @param $tree             树级数组
     * @param $start            开始节点
     * @param $id               ID字段名
     * @param $name             标题字段名
     * @param array $checked    默认选中的数组
     * @param bool $flag        是否返回
     * @return mixed|string|void
     */
    public function echoTree($tree, $start, $id, $name, $checked=array(), $flag=false) {
    	$this->layout = '';
    
    	$tree = array(
    			'tree' => $tree,
    			'start' => $start,
    			'id' => $id,
    			'name' => $name,
    			'checked' => $checked
    	);
    
    	return $this->render('menu_tree', $tree, $flag);
    }
    
    
    public function doGrant(){
    	$role   = $this->R('role');
    	$add    = $this->R('add');
    	$delete = $this->R('delete');
    
    	if(RoleaService::grantMenu($role, $add, $delete)){
    		$this->out = 1;
    	}else{
    		$this->out = 2;
    	}
    	$this->outType = 'json';
    }

   

} 